package net.gamebookengine.viewer;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;

public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener
{
	private SharedPreferences				sharedPreferences;
	private final Map<Preference, String>	preferenceMap	= new HashMap<Preference, String>();
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.preferences);
		
		PreferenceScreen preferenceScreen = getPreferenceScreen();
		sharedPreferences = preferenceScreen.getSharedPreferences();
		
		fillPreferenceList(preferenceScreen);
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		sharedPreferences.registerOnSharedPreferenceChangeListener(this);
		updateSummary();
	}
	
	@Override
	protected void onPause()
	{
		super.onPause();
		sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
	}
	
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
	{
		updateSummary();
	}
	
	private void fillPreferenceList(PreferenceGroup preferenceGroup)
	{
		int preferenceCount = preferenceGroup.getPreferenceCount();
		for (int preferenceIndex = 0; preferenceIndex < preferenceCount; preferenceIndex++)
		{
			Preference preference = preferenceGroup.getPreference(preferenceIndex);
			
			if (preference instanceof PreferenceGroup)
			{
				fillPreferenceList((PreferenceGroup) preference);
			}
			else
			{
				String summary = preference.getSummary().toString();
				if (summary.contains("%s"))
				{
					preferenceMap.put(preference, summary);
				}
			}
			
		}
	}
	
	private void updateSummary()
	{
		Map<String, ?> sharedPreferencesMap = sharedPreferences.getAll();
		
		for (Entry<Preference, String> entry : preferenceMap.entrySet())
		{
			Preference preference = entry.getKey();
			String preferenceKey = preference.getKey();
			String newSummary = String.format(entry.getValue(), sharedPreferencesMap.get(preferenceKey));
			preference.setSummary(newSummary);
		}
	}
}